package com.heima.kafka.sample;

import org.apache.kafka.clients.consumer.*;
import org.junit.Test;

import java.time.Duration;
import java.util.Collections;
import java.util.Properties;

/**
 * 消费者
 */
public class ConsumerQuickStart {

    @Test
    public void testReceiveMsg() {
        // 添加消费者配置
        Properties properties = new Properties();
        // 添加连接配置
        properties.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "81.68.105.177:9092");
        // 添加消费者分组
        properties.put(ConsumerConfig.GROUP_ID_CONFIG, "xiaoheizi");
        // 添加消费者key反序列化器
        properties.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG,
                "org.apache.kafka.common.serialization.StringDeserializer");
        // 添加value反序列化器
        properties.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG,
                "org.apache.kafka.common.serialization.StringDeserializer");

        // 创建消费者核心对象
        Consumer<String, String> consumer = new KafkaConsumer<String, String>(properties);

        // 设置接收消息的topic
        consumer.subscribe(Collections.singletonList("666"));

        // 获取消息,每秒钟拉取一次消息
        while (true) {
            ConsumerRecords<String, String> records = consumer.poll(Duration.ofMillis(1000));
            // 获取到消息
            for (ConsumerRecord<String, String> record : records) {
                System.out.println(record.key() + "--->" + record.value());
            }
        }
    }


}
